import { PlusOutlined, SettingOutlined, DeleteOutlined } from '@ant-design/icons';
import { Button, Table, Space, Row, Col } from 'antd';
import React, { useMemo, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import { t } from '@/locales/i18n';
import { FlowNodeInputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeInputItemType } from '@/types/workflow/io';

import { WorkflowContext } from '../../../../context';

import EditFieldModal from './EditFieldModal';

import type { ColumnsType } from 'antd/es/table';

function RenderToolInput({ nodeId, inputs }: { nodeId: string; inputs: FlowNodeInputItemType[] }) {
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);
  const splitToolInputs = useContextSelector(WorkflowContext, (ctx) => ctx.splitToolInputs);
  const { toolInputs } = splitToolInputs(inputs, nodeId);

  const dynamicInput = useMemo(() => {
    return inputs.find((item) => item.renderTypeList[0] === FlowNodeInputTypeEnum.addInputParam);
  }, [inputs]);

  const [editField, setEditField] = useState<FlowNodeInputItemType>();

  const columns: ColumnsType<FlowNodeInputItemType> = [
    {
      title: t('item_name'),
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: t('item_description'),
      dataIndex: 'toolDescription',
      key: 'toolDescription',
    },
    {
      title: t('required'),
      dataIndex: 'required',
      key: 'required',
      render: (required: boolean) => (required ? '✔' : ''),
    },
  ];

  if (dynamicInput) {
    columns.push({
      title: '',
      key: 'action',
      render: (_: unknown, record: FlowNodeInputItemType) => (
        <Space>
          <SettingOutlined style={{ cursor: 'pointer' }} onClick={() => setEditField(record)} />
          <DeleteOutlined
            style={{ cursor: 'pointer' }}
            onClick={() => {
              onChangeNode({
                nodeId,
                type: 'delInput',
                key: record.key,
              });
            }}
          />
        </Space>
      ),
    });
  }

  return (
    <div className="flex flex-col px-3">
      <Row justify="space-between">
        <span className="mb-2 text-xs font-font-weight-600 text-text-4">{t('tool_input')}</span>
        {dynamicInput && (
          <Col>
            <Button size="small" icon={<PlusOutlined />} onClick={() => setEditField(undefined)}>
              {t('add_new')}
            </Button>
          </Col>
        )}
      </Row>

      <Table
        columns={columns}
        dataSource={toolInputs}
        rowKey="key"
        pagination={false}
        size="small"
      />

      {!!editField && (
        <EditFieldModal
          defaultValue={editField}
          nodeId={nodeId}
          onClose={() => setEditField(undefined)}
        />
      )}
    </div>
  );
}

export default React.memo(RenderToolInput);
